//
//  FakeNaviBar.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/31.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import Foundation
import UIKit

@objc class FakeNaviBar: UIView {
    
    @IBOutlet var effectView: UIVisualEffectView?
    @IBOutlet var titleLabel: UILabel?
    
    /// 如果设置了关联的 UIScrollView 且 autoHideBg == true 将自动根据 UIScrollView的offset情况来调整背景透明度
    /// 可以通过设置 autoHideOffset 来指定参考的 offset，不指定时默认为 FakeNaviBar 的height
    /// 当UIScrollView的offset 小于参考的offset时将隐藏背景。
    @IBOutlet weak var relatedScrollView: UIScrollView?
    @IBInspectable var autoHideBackground: Bool = true
    private var _autoHideOffset: CGFloat?
    @IBInspectable var autoHideOffset: CGFloat = 0 {
        didSet {
            _autoHideOffset = autoHideOffset
        }
    }
    
    private var observation: NSKeyValueObservation?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        if let view = relatedScrollView {
            observation = view.observe(\UIScrollView.contentOffset) { [weak self] scrollView, change in
                self?.onScrollViewOffsetChanged(scrollView)
            }
        }
    }
    
    deinit {
        print("----- \(self) deinit -----")
    }
    
    private func onScrollViewOffsetChanged(_ view: UIScrollView) {
        guard autoHideBackground, view === relatedScrollView else { return }
        let offset = view.contentOffset.y
        let referOffset = _autoHideOffset ?? -bounds.height
        if offset > referOffset {
            self.effectView?.isHidden = false
        } else {
            self.effectView?.isHidden = true
        }
    }
}
